﻿<%@ Page Title="Promotion Engine -  User Defined Report" Language="C#" MasterPageFile="~/Site.Master"
    AutoEventWireup="true" CodeBehind="ReportUserDefined.aspx.cs" Inherits="PromotionEngine.ReportUserDefined" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <style>
        .k-edit-label, .k-edit-form-container .editor-label
        {
           text-align: left; 
            width: 30%;
            margin-left: 0%;
        }
        .k-edit-field, .k-edit-form-container .editor-field
        {
            float: left;
            clear: right;
            width: 200px;
        }
    </style>
    <script type="text/javascript">
        var reportID;
        var reportName;
        var grid;
        $(document).ready(function () {
            reportID = '<%= Request.QueryString["ReportID"] %>';
            reportName = '<%= Request.QueryString["ReportName"] %>';
            $('#ReportName').text(reportName);
            CreateParaControls();



        });
        function CreateParaControls() {
            $.ajax({
                type: "POST",
                url: "ReportUserDefined.aspx/GetReportParameter",
                data: JSON.stringify({
                    reportID: reportID
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var result = JSON.parse(response.d);
                    if (result) {
                        if (result.length > 0) {
                            var dateControls = [];
                            var dropDownListControls = [];
                            var dropDownListControlsObj = {};
                            for (var i = 0; i < result.length; i++) {
                                var newTextBoxDiv = $(document.createElement('div'))
	                             .attr("id", 'TextBoxDiv' + i);

                                if (result[i].ReferenceName == 'Numeric') {
                                    newTextBoxDiv.after().html(' <div class="k-edit-label"><label>' + result[i].ParaCaption + '  </label></div>' +
	                              '<div class="k-edit-field" ><input onkeyup="allowNumericNumber(this)" type="text" id="' + result[i].ParaName.replace('@', '') + '" name="' + result[i].ParaName.replace('@', '') + '" class="k-input k-textbox"/></div>');
                                }
                                else if (result[i].ReferenceName == 'Alphanumeric') {
                                    newTextBoxDiv.after().html(' <div class="k-edit-label"><label>' + result[i].ParaCaption + '  </label></div>' +
	                              '<div class="k-edit-field" ><input type="text" id="' + result[i].ParaName.replace('@', '') + '" name="' + result[i].ParaName.replace('@', '') + '" class="k-input k-textbox"/></div>');
                                }
                                else if (result[i].ReferenceName == 'Date time') {
                                    newTextBoxDiv.after().html(' <div class="k-edit-label"><label>' + result[i].ParaCaption + '  </label></div>' +
	                              '<div class="k-edit-field" ><input id="' + result[i].ParaName.replace('@', '') + '" name="' + result[i].ParaName.replace('@', '') + '"  /></div>');
                                    dateControls.push(result[i].ParaName.replace('@', ''));

                                }
                                else if (result[i].ReferenceName == 'Boolean') {
                                    newTextBoxDiv.after().html(' <div class="k-edit-label"><label>' + result[i].ParaCaption + '  </label></div>' +
	                              '<div class="k-edit-field"  style="width: 20px;margin-top: 4px;"><input type="checkbox" id="' + result[i].ParaName.replace('@', '') + '" name="' + result[i].ParaName.replace('@', '') + '""/></div>');
                                }
                                else if (result[i].ReferenceName == 'Query') {
                                    newTextBoxDiv.after().html(' <div class="k-edit-label"><label>' + result[i].ParaCaption + '  </label></div>' +
	                              '<div class="k-edit-field" ><input id="' + result[i].ParaName.replace('@', '') + '" name="' + result[i].ParaName.replace('@', '') + '"  /></div>');
                                    dropDownListControlsObj[result[i].ParaName.replace('@', '')] = result[i].ReportDetailID
                                    dropDownListControls.push(dropDownListControlsObj);
                                }

                                newTextBoxDiv.appendTo("#TextBoxesGroup");
                            }
                            if (dateControls.length > 0) {
                                for (var fieldIndex = 0; fieldIndex < dateControls.length; fieldIndex++) {
                                    $("#" + dateControls[fieldIndex]).kendoDatePicker({
                                        value: new Date()
                                    }).data("kendoDatePicker");
                                }
                            }
                            if (dropDownListControlsObj != null) {
                                for (var fieldIndex = 0; fieldIndex < dropDownListControls.length; fieldIndex++) {
                                    $.each(dropDownListControls[fieldIndex], function (key, value) {
                                        // Start 
                                        $("#" + key).kendoDropDownList({
                                            autoBind: false,
                                            filter: "contains",
                                            optionLabel: "[Select Parameter Value]",
                                            dataTextField: "Name",
                                            dataValueField: "Value",
                                            suggest: true,
                                            required: true,
                                            dataSource: {
                                                transport: {
                                                    read: {
                                                        type: "GET",
                                                        url: "ReportUserDefined.aspx/LoadReportParaFromQuery",
                                                        contentType: "application/json; charset=utf-8",
                                                        dataType: "json"
                                                    },
                                                    parameterMap: function (data, operation) {
                                                        if (operation === "read") {
                                                            return { reportDetailID: value };
                                                        }
                                                    }
                                                },
                                                type: "json", //Important!!!!
                                                schema: {
                                                    data: function (response) {
                                                        if (response.d != null) {
                                                            var data = response.d;
                                                            return JSON.parse(data);
                                                        }
                                                    },
                                                    allowCustomValues: false,
                                                    model: {
                                                        id: "Value",
                                                        fields: {
                                                            Value: { type: "string", validation: { required: true} },
                                                            Name: { type: "string", validation: { required: true} }
                                                        }
                                                    }
                                                }
                                            }
                                        });
                                     // End 
                                    });
                                }
                            }
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        //Get All Item
        function LoadReport() {
            var params = {};
            $('#grid').empty();
            var listTextBox = $("#aspnetForm").find($('input[type="text"]'));
            for (var i = 0; i < listTextBox.length; i++) {
                var name = listTextBox[i].name;
                name = name.replace('@', '');
                var value = $("#" + name).val();
                if (value.length == 0) {
                    setMasterMessage("Please input all parameter", "error");
                    return;
                }
                else {
                    params[name] = value;
                }
            }
            var dropDownList = $("#aspnetForm").find($('input'));
            for (var i = 0; i < dropDownList.length; i++) {
                var name = dropDownList[i].name;
                name = name.replace('@', '');
                if (name != '__VIEWSTATE' && name != '__VIEWSTATEGENERATOR') {
                    if ($('#' + name).data("kendoDropDownList") != null) {
                        var value = $('#' + name).data("kendoDropDownList").value();
                        if (value.trim().length == 0) {
                            setMasterMessage("Please input all parameter", "error");
                            return;
                        }
                        else {
                            params[name] = value
                        }
                    }
                }
            }
            getValueCheckBox(params);
            $.ajax({
                type: "POST",
                url: "ReportUserDefined.aspx/LoadReport",
                data: JSON.stringify({
                    reportID: reportID,
                    oParams: JSON.stringify(params)
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function OnSuccess(response) {
            var data = response.d;
            if (data.length > 0) {
                var data = $.parseJSON(response.d);
                var dateFields = [];
                generateGrid(data)
                function generateGrid(gridData) {

                    var model = generateModel(gridData[0]);

                    var parseFunction;
                    if (dateFields.length > 0) {
                        parseFunction = function (response) {
                            for (var i = 0; i < response.length; i++) {
                                for (var fieldIndex = 0; fieldIndex < dateFields.length; fieldIndex++) {
                                    var record = response[i];
                                    record[dateFields[fieldIndex]] = kendo.parseDate(record[dateFields[fieldIndex]]);
                                }
                            }
                            return response;
                        };
                    }

                    grid = $("#grid").kendoGrid({
                        dataSource: {
                            data: gridData,
                            schema: {
                                model: model//,
                                //parse: parseFunction
                            }
                        },
                        pageable: {
                            pageSize: 8,
                            refresh: true
                        },
                        toolbar: [{ name: 'excel'}],
                        excel: {
                            fileName: "Report Data.xlsx",
                            filterable: true,
                            allPages: true
                        },
                        reorderable: true,
                        sortable: true,
                        groupable: true

                    });
                }

                function generateModel(gridData) {
                    var model = {};
                    model.id = "ID";
                    var fields = {};
                    for (var property in gridData) {
                        var propType = typeof gridData[property];
                        if (propType == "number") {
                            fields[property] = {
                                type: "number",
                                validation: {
                                    required: true
                                }
                            };
                        } else if (propType == "boolean") {
                            fields[property] = {
                                type: "boolean",
                                validation: {
                                    required: true
                                }
                            };
                        } else if (propType == "string") {
                            var parsedDate = kendo.parseDate(gridData[property]);
                            if (parsedDate) {
                                fields[property] = {
                                    type: "date",
                                    validation: {
                                        required: true
                                    }
                                };
                                dateFields.push(property);
                            } else {
                                fields[property] = {
                                    validation: {
                                        required: true
                                    }
                                };
                            }
                        } else {
                            fields[property] = {
                                validation: {
                                    required: true
                                }
                            };
                        }

                    }
                    model.fields = fields;

                    return model;
                }
            }
        }
    </script>
    <table style="width: 100%;" border="0px">
        <tr style="height: 25px;">
            <td align="center" style="font-weight: 700; color: #CC3300; font-size: 14pt;" valign="top">
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span class="k-icon k-i-tick"></span> Report Parameters
            </td>
            <td style="font-weight: 700; color: #CC3300; font-size: 14pt;" valign="top">
                <span class="k-icon k-i-tick"></span> <span id="ReportName"></span>
            </td>
        </tr>
        <tr>
            <td style="width: 320px;" valign="top" align="left">
                <div id='TextBoxesGroup' style="margin-left: 0px; margin-top:5px;">
                </div>
                <div class="k-edit-label">
                    <label>
                    </label>
                </div>
                <div class="k-edit-field">
                    <button type="button" id="btnSave" onclick="LoadReport();" class="k-button k-button-icontext k-primary"
                        style="width: 200px; margin-right: 25px;">
                        <span class="k-icon k-i-tick"></span>View Report</button></div>
            </td>
            <td valign="top">
                <div id="grid" style=" margin-top:5px;">
                </div>
            </td>
        </tr>
    </table>
</asp:Content>
